package databaseVersionControl.domain.dml;

import java.util.Map;
import java.util.TreeMap;

import databaseVersionControl.infra.exception.DVCGeneralException;

public class Update extends DML {

	private String whereStatement;
	private TreeMap<String, Object> fields;

	public Update(String table) {
		this.table = table;
	}

	public Update set(Map<String, Object> map) {
		if (map != null) fields = new TreeMap<String, Object>(map);
		return this;
	}

	public Update where(String where) {
		whereStatement = where;
		return this;
	}

	@Override
	public String sqlString() {
		StringBuilder builder = new StringBuilder();
		builder.append("UPDATE ");
		builder.append(this.table.toUpperCase());
		if (fields == null) throw new DVCGeneralException("You can't update without specify fields");
		builder.append(" SET " + valuesToUpdate());
		if(whereStatement != null) builder.append(" WHERE " + whereStatement);
		return builder.toString();
	}

	private String valuesToUpdate() {
		StringBuilder builder = new StringBuilder();
		builder.append(fields.firstKey());
		builder.append("=");
		builder.append("'"+fields.firstEntry().getValue());
		fields.remove(fields.firstKey());
		for (String key : fields.keySet()) builder.append("', " + key + "='" + fields.get(key));
		return builder.append("'").toString();
	}

}
